"""
工具函数模块，包含日志记录和重试装饰器。
"""

import logging
import structlog
from functools import wraps
from time import sleep
from typing import Callable, Any


# 配置结构化日志
def configure_logging() -> None:
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    )
    structlog.configure(
        processors=[
            structlog.processors.add_log_level,
            structlog.processors.JSONRenderer()
        ],
        context_class=dict,
        logger_factory=structlog.stdlib.LoggerFactory(),
    )


def retry(max_retries: int = 3, delay: int = 1) -> Callable:
    """
    重试装饰器，用于处理可能失败的操作。
    """

    def decorator(func: Callable) -> Callable:
        @wraps(func)
        async def wrapper(*args, **kwargs) -> Any:
            retries = 0
            while retries < max_retries:
                try:
                    return await func(*args, **kwargs)
                except Exception as e:
                    retries += 1
                    if retries >= max_retries:
                        raise
                    logger = logging.getLogger(__name__)
                    logger.warning(f"Retrying  {func.__name__} (attempt {retries}/{max_retries})")
                    sleep(delay)

        return wrapper

    return decorator



